package com.hjk.waibao.mj.controller;

import cn.hutool.core.util.StrUtil;
import com.hjk.waibao.mj.annotation.LoginUser;
import com.hjk.waibao.mj.annotation.PostPara;
import com.hjk.waibao.mj.bean.ApiResult;
import com.hjk.waibao.mj.bean.SessionKey;
import com.hjk.waibao.mj.common.model.User;
import com.hjk.waibao.mj.exception.CustomException;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.jfinal.json.Json;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Page;

import java.util.UUID;

/**
 * @author hjk
 */
public class UserController extends Controller {
    public static String emailRegex = "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$";
    public static String phoneRegex = "^1[3456789]\\d{9}$";
    public static String adminId = PropKit.get("admin_id");

    public void index() {

    }

    public void info(@LoginUser User user) {
        User result = new User();
        result.put(user);
        result.setPassword(null);
        renderJson(ApiResult.createSuccess(result));
    }

    public void getUserInfo(@LoginUser User user, @Para String userId) throws CustomException {
        renderJson(ApiResult.createSuccess(user));
    }

    public void list(@Para Integer pageSize, @Para Integer pageNumber,
                     @LoginUser User user, @PostPara String id, @PostPara String userName, @PostPara String companyName,
                     @PostPara String email, @PostPara String phone) {
        Page<User> page = User.dao.paginate(pageNumber, pageSize,
                "select * ", " from t_user where 1=1 and `name` like ? and companyName like ? and email like ? and phone like ? and id != ? and id like ? order by id desc",
                '%' + userName + '%', '%' + companyName + '%', '%' + email + '%', '%' + phone + '%', adminId, '%' + id + '%'
        );
        renderJson(ApiResult.createSuccessWithJsonData("", Json.getJson().toJson(page)));

    }

    public void login(@PostPara String username, @PostPara String password) throws CustomException {
        User user = User.dao.findFirst("select * from t_user where (username=? or phone=?) and password=?", username, username, password);
        if (user == null) {
            throw new CustomException("用户名密码错误");
        }
        setCookie("sessionKey", SessionKey.getSessionKey(user.getId()).getKey(), 3600);
        renderJson(ApiResult.createSuccess("登录成功", SessionKey.getSessionKey(user.getId()).getKey()));
    }

    public void userLogin(@LoginUser User user) {
        if (user != null && user.getUsername() != null) {
            redirect("/");
        } else {
            render("userLogin.html");
        }
    }

    public void loginSubmit(@PostPara String username, @PostPara String password) throws CustomException {
        User user = User.dao.findFirst("select * from t_user where (username=? or phone=?) and password=?", username, username, password);
        if (user == null) {
            throw new CustomException("user not exists or password incorrect");
        }
        setCookie("sessionKey", SessionKey.getSessionKey(user.getId()).getKey(), 3600);
        renderJson(ApiResult.createSuccess("login success", SessionKey.getSessionKey(user.getId()).getKey()));
    }

    public void logout() throws CustomException {
        setCookie("sessionKey", "", 3600);
        redirect("/");
    }

    public void registerSubmit(@PostPara String username, @PostPara String password) throws CustomException {
        User user = User.dao.findFirst("select * from t_user where username=? ", username);
        if (user != null) {
            throw new CustomException("the user is already exists");
        }
        user = new User();
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setUsername(username);
        user.setPassword(password);
        user.save();
        setCookie("sessionKey", SessionKey.getSessionKey(user.getId()).getKey(), 3600);
        renderJson(ApiResult.createSuccess("login success", SessionKey.getSessionKey(user.getId()).getKey()));
    }

    public void registerOrLoginSubmit(@PostPara String username, @PostPara String password) throws CustomException {
        User user = User.dao.findFirst("select * from t_user where username=? ", username);
        if (user != null) {
            if (StrUtil.equals(password, user.getPassword())) {
                setCookie("sessionKey", SessionKey.getSessionKey(user.getId()).getKey(), 3600);
                renderJson(ApiResult.createSuccess("login success", SessionKey.getSessionKey(user.getId()).getKey()));
            } else {
                throw new CustomException("password incorrect");
            }
        } else {
            user = new User();
            user.setId(UUID.randomUUID().toString().replace("-", ""));
            user.setUsername(username);
            user.setPassword(password);
            user.save();
            setCookie("sessionKey", SessionKey.getSessionKey(user.getId()).getKey(), 3600);
            renderJson(ApiResult.createSuccess("login success", SessionKey.getSessionKey(user.getId()).getKey()));
        }
    }

    public void loginValidate() {
        if (!validateCaptcha("captcha")) {
            renderJson(ApiResult.createFailJson("验证码错误"));
            return;
        }
        User user = User.dao.findFirst("select * from t_user where phone=? and password=?", getAttr("phone"), getAttr("password"));
        if (user == null) {
            renderJson(ApiResult.createFailJson("账号或密码错误"));
            return;
        }
        setCookie("sessionKey", SessionKey.getSessionKey(user.getId()).getKey(), 3600);
        if (adminId.equals(user.getId())) {
            renderJson(ApiResult.createSuccessJson("登录成功", "/adminIndex"));
        } else {
            renderJson(ApiResult.createSuccessJson("登录成功", "/userIndex"));
        }
    }
}

